20180717 Python文字辨識

嗨,我還在寫歐,前一陣子跑去學html跟CSS了,所以這邊有些擱置了。

最近因為生活上的需求,打算將筆記上的字轉成文字檔,
稍微查詢了一下,有個好用的套件叫做tesseract-ocr,
先說結論,tesseract-ocr基本上是沒辦法處理手寫的文字圖片,
沒錯,基本上只能辨識"英文"的"電腦書寫"的圖片檔。
如果要做文字訓練又是另外一回事了,實在不符成本,
決定先放棄這條艱辛路。
這邊只做基本整理,需要哪些模塊,和簡單的執行文字辨識。

[事前準備]
1.安裝pillow (pip3 install pillow)
為PIL (Python Imaging Library)的持續維護版,
可以在python進行圖形處理。
https://pillow.readthedocs.org/

2.安裝tesseract-ocr (wiki) 一個流行的OCR,光學識別模塊(Optical Character Recognition),
原本由HP開發,2006年開始由google維護的開源項目。

3.安裝pytesseract (pip3 install pytesseract)
基本上就是跟tesseract對接的python模組而已。

4.修改pytesseract文本或是將tesseract位置設成環境PATH或 如果你去確認pytesseract的py檔的話,
會發現這條:

# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH, OR IS NAMED DIFFERENTLY
tesseract_cmd = 'tesseract'

只要將'tesseract'取代成你的安裝位置就可以了,
或是你可以新增一條環境變數 (進階系統設定>進階>環境變數>Path>編輯>新增tesseract-ocr安裝位置)
總之要讓pytesseract可以把tesseract開得起來就是了。

接下來...編碼就這樣:

import pytesseract
from PIL import Image

image = Image.open('C:\\Users\\Ramone\\test.png') #此為你要識別文字的圖檔位置
code = pytesseract.image_to_string(image)

print(code)

如果想要存成檔案的話編碼把它改成這樣:

import pytesseract
from PIL import Image
import os  #python的目錄操作模組

#定義一個function
def ocr(file_to_ocr):
    im = Image.open(file_to_ocr)
    text = pytesseract.image_to_string(im)

    # 用with open方式,將辨識結果text,在原路徑儲存一個原檔名的txt檔,
    # 記得編碼utf8,否則會錯誤(預設不知為何為big5)
    with open(file_to_ocr+'.txt','w',encoding='utf8') as f: 
        f.write(text)
    return txt

print (ocr('./test.png'))

(註) pytesseract辨識中文的語法如下:

pytesseract.image_to_string(image, lang='chi_tra')

results matching ""

    No results matching ""